package com.bilibili.juc.completableFuture;

import java.util.concurrent.*;

/**
 * @author zuife
 * @description
 * @since 2024-04-20 13:45:16
 */
public class CompletableFutureUseDemo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName()+"-------come in");
                int result =ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if(result>5){
                    int i=10/0;
                }
                System.out.println("----------1秒后出结果");
                return result;
            },threadPool).whenComplete((v,e)->{
                System.out.println("----"+v);
                if(e==null){
                    System.out.println("----计算完成，更新系统updateValue:"+v);
                }
            }).exceptionally(e->{
                System.out.println("----计算出现异常" +e.getCause()+"\t"+e.getMessage());
                e.printStackTrace();
                return null;
            });
            System.out.println(Thread.currentThread().getName()+"线程先去忙其他任务");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常情况"+e.getCause()+"\t"+e.getMessage());
            threadPool.shutdown();
        }
    }
}
